# doc文档转为docx文档，再转pdf，在pdf中提取特定页数，保存为新文件
import glob
import sys

# import office
from PyPDF2 import PdfReader, PdfWriter
from qgis.PyQt import QtWidgets, QtCore
from qgis.PyQt import uic
from pprint import pprint
sys.path.append('../')
from tool.utils import *

# office.word.docx2pdf(path,pdf_out_path)
pages = [7]
# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
FORM_CLASS, _ = uic.loadUiType(os.path.join(
    Ui_path, 'one_file_input_template.ui'))


class getpdfpageDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, parent=None):
        """Constructor."""
        super(getpdfpageDialog, self).__init__(parent)

        self.setupUi(self)

        self.setWindowTitle('提取pdf页面')
        self.label.setText('pdf文件夹')
        self.mQgsFileWidget.setStorageMode(1)
        self.buttonBox.accepted.connect(self.pdfmerge)
        self.lineedit1 = QtWidgets.QLineEdit('提取页面页数')
        self.horizontalLayout1 = QtWidgets.QHBoxLayout()
        self.horizontalLayout1.addWidget(self.lineedit1)
        self.horizontalLayout1.setAlignment(QtCore.Qt.AlignVCenter)
        self.verticalLayout.insertLayout(1, self.horizontalLayout1)

    def tool_name(self):
        return '提取pdf页面'

    def tab_class(self):
        return '无人机'

    def pdfmerge(self):
        pdf_writer = PdfWriter()
        path = self.mQgsFileWidget.filePath()
        # pprint(glob.glob(path+'/*.pdf'))
        page = [7]
        lists = os.listdir(path)
        for pdf_file in lists:
            pdf = PdfReader(path + "\\" + pdf_file)
            num = len(pdf.pages)
            if num == 10:
                for page in pages:
                    pdf_writer.add_page(pdf.pages[page])
            elif num == 11:
                for page in pages:
                    pdf_writer.add_page(pdf.pages[page + 1])

        output_file = path + "\\" + "out.pdf"
        with open(output_file, 'wb') as output_pdf:
            pdf_writer.write(output_pdf)
        print("打包成功")


if __name__ == '__main__':
    from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QPlainTextEdit

    app = QApplication([])
    dlg = getpdfpageDialog()

    dlg.show()
    app.exec_()
